// index.js
const CryptoJS = require('../../utils/crypto-js.js')

Page({
  data: {
    itrahost:"https://itra.run",
    title:"ITRA越野表现",
    notice_text:"小程序非官方123，查看单场表现分请访问官方平台:https://itra.run",
    lastname:"",
    firstname:"",
    itraId:"",
    currentIndex:0,
    pageSize:10,
    currentTab:0,
    isLoading:false,
    list: []
  },
   
    onReady:function(){
      var va1 = wx.getStorageSync('lastname');
      var va2 = wx.getStorageSync('firstname');
      var va3 = wx.getStorageSync('itraid');
      this.setData({
          lastname : va1,
          firstname :va2,
          itraId:va3
        }
      );
      this.getnotice();
    },

    onLastNameInputChange:function(options){
      let value = options.detail.value;
      this.setData({
        lastname: value
      })
    },

  onFirstNameInputChange(e) {
      let inputName = e.detail.value
      this.setData({
        firstname: inputName
      })
    },

    onItraIdInputChange(e) {
      let value = e.detail.value
      this.setData({
        itraId: value
      })
    },
    
  onItem:function(e){
      var index = e.currentTarget.id;
      var obj = this.data.list[index];
      var info = {
        'firstName':obj.firstName,
        'lastName':obj.lastName,
        'runnerId':obj.runnerId,
        'gender':obj.gender,
        'nationality':obj.nationality,
        'profilePic':obj.profilePic
      };
      var str = encodeURIComponent(JSON.stringify(info));
      wx.navigateTo({
        url: '../mine/mine?str='+str
      })
    },
    onDelete:function(e){
      var index = e.currentTarget.id;
      this.data.list.splice(index,1);
      var strj = JSON.stringify(this.data.list);
      wx.setStorageSync('myfavs', strj);
      this.setData({
        list:this.data.list
      }
      )
    },

  onQuery:function(e){
      if(this.data.currentTab==0){
        if(!this.data.firstname || !this.data.lastname){
          wx.showModal({
            content: "请输入您的姓或名拼音",
            showCancel:false,
            confirmColor:"#000000"
          })
        }else{
          wx.setStorageSync('lastname', this.data.lastname);
          wx.setStorageSync('firstname', this.data.firstname);
          if (this.data.isLoading) {
              return; // 如果已经在加载中，直接返回
          }
          this.setData({
            isLoading: true
          });
          this.requestITRAPrefData()
        }  
      }else{
        if(!this.data.itraId){
          wx.showModal({
            content: "请输入您的ITRA ID",
            showCancel:false,
            confirmColor:"#000000"
          })
        }else{
          wx.setStorageSync('itraid', this.data.itraId);
          if (this.data.isLoading) {
              return; // 如果已经在加载中，直接返回
          }
          this.setData({
            isLoading: true
          });
          this.itra_info(this.data.itraId);
        }
      }
    },
    
    //ITRA助手请求数据
    requestITRAPrefData:function(){
      const app = getApp();
      var name = this.data.lastname+" "+this.data.firstname;
      console.log('name=='+name);
      console.log('==url=='+app.globalData.searchUrl);
      wx.request({
        url: app.globalData.searchUrl,
        data:{
          "name":name,
          "pageNum":1,
          "pageSize":this.data.pageSize,
          'echoToken':0.009322270910500974
        },
        header:{
          "Accept-Encoding": "gzip, deflate, br",
          "Accept": "*/*",
          "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
          "Referer": "https://itra.run/Account/Login",
          "Connection": "keep-alive",
          "Cookie":".AspNetCore.Antiforgery.KYulInBaheU=CfDJ8Nxp6PWsRBxPlLMXliNHvxJ3EIM8vtmolD-M0g04KUkrC9YLiSIhkLPx_OWHRx1jne_WTHMBdIMcCUQ_rl9creqVlU4daY1Np_ZRThxEFpCLcT_KqEaH4ssR2SPsw1yYULB8OlXjfU4mTPTmsoeGNUE;"
        },
        method:"POST",
        success:(res)=>{
          this.setData({
            isLoading: false
          });
          var data = res.data;
          console.log('code==='+data.code)
          console.log('msg==='+data.msg)
          if(data.code==1){
            var dataVa = data.data;
            // var ciphertext_b64 = response.response1;
            // if(response != null && ciphertext_b64!=null && ciphertext_b64.length!=0){
              // var iv_b64 = response.response2;
              // var key_b64 = response.response3;
              // const key = CryptoJS.enc.Base64.parse(key_b64);
              // const iv = CryptoJS.enc.Base64.parse(iv_b64);
              // const ciphertext = CryptoJS.enc.Base64.parse(ciphertext_b64);
              // const decrypted = CryptoJS.AES.decrypt(
              //     { ciphertext: ciphertext },
              //     key,
              //     {
              //       iv: iv,
              //       mode: CryptoJS.mode.CBC,
              //       padding: CryptoJS.pad.Pkcs7
              //     }
              //   );
              // const plaintext = decrypted.toString(CryptoJS.enc.Utf8);
              // const jsonData = JSON.parse(plaintext);
              // console.log(plaintext);
              var results = dataVa.results;
              console.log(results);
              if(results.length==0){
                wx.showModal({
                  content: "未查询到相关数据，请确保姓名拼音输入正确!",
                  showCancel:false,
                  confirmText:"确定",
                  confirmColor:"#000000"
                })
              }else{
                var va = encodeURIComponent(JSON.stringify(results));
                wx.navigateTo({
                  url: '../search/search?list='+va+"&name="+name+"&isback=1&firstname="+this.data.firstname+"&lastname="+this.data.lastname
                })
              }
                  
            // }else{
            //   wx.showToast({
            //     title: 'ITRA请求失败，请稍后再试!',
            //     icon:"none",
            //     duration:2500
            //   })
            // }
          }else{
            wx.showToast({
              title: data.msg,
              icon:"none",
              duration:2500
            })
          }
        },
        fail: (err) => {//请求失败
          this.setData({
            isLoading: false
          });
          wx.showModal({
            title: '温馨提示',
            content: "网络较慢,数据请求失败!",
            showCancel:false,
            confirmText:"确定",
            confirmColor:"#000000"
          })
        }
      })
    },
    
    itra_info:function(itraid){
      var that = this;
      const app = getApp();
      wx.request({
        url: app.globalData.itra_info,
        method:"GET",
        success:(res)=>{
          var response = res.data;
          console.log(response);
          var session = response.Session;
          var application = response.Application;
          that.queryItraDataBack(itraid,session,application);
        },
        fail: (err) => {
          this.setData({
            isLoading: false
          });
          wx.showModal({
            title: '温馨提示',
            content: "网络较慢,数据请求失败!",
            showCancel:false,
            confirmText:"确定",
            confirmColor:"#000000"
          })
        }
      })
  },
  queryItraDataBack:function(itraid,session,application){
    var that = this;
    const app = getApp();
    wx.request({
      url: app.globalData.dataRunnerUrl+itraid,
      header:{
        "Accept-Encoding": "gzip, deflate, br",
        "Accept": "*/*",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Connection": "keep-alive",
        'Cookie': '.AspNetCore.Session='+session+'; .AspNetCore.Identity.Application='+application
      },
      method:"GET",
      success:(res)=>{
        var results = res.data;
        var id = results.id;
        console.log(results);
        that.setData({
          isLoading:false,
        })
        if (id==null || id=='') {
          console.log('data 为空');
          app.refreshToken();
          wx.showToast({
            title: 'ITRA服务不稳定，请稍后再试',
            icon:"none",
            duration:2500
          })
        } else {
            var score = results['pi'];
            var info = {
                'firstName':results['firstName'],
                'lastName':results['lastName'],
                'runnerId':itraid,
                'gender':results['gender'],
                'nationality':'https://itra.run/images/CountryFlags/'+results['code']+'.svg',
                'profilePic':'https://itra.run/Files/Photos/'+results['profilePicture'],
                'pi':score
            };
            var str = encodeURIComponent(JSON.stringify(info));
            wx.navigateTo({
              url: '../mine/mine?str='+str
            })
        }
      },
      fail: (err) => {
        this.setData({
          isLoading: false
        });
        wx.showModal({
          title: '温馨提示',
          content: "网络较慢,数据请求失败!",
          showCancel:false,
          confirmText:"确定",
          confirmColor:"#000000"
        })
      }
    })
  },

  
  //分享
  onShareAppMessage:function(){
    this.setData({
      lastname:"",
      firstname:""
    });
    return {
      title: "ITRA越野积分、表现分快捷查询"
    };
  },

  onShareTimeline:function(){
    this.setData({
      lastname:"",
      firstname:""
    });
    return {
      title: "ITRA越野积分、表现分快捷查询"
    };
  },
  //清空
  onClearLastName:function(e){
    this.setData({
      lastname: ''
    })
  },
  onClearFirstName:function(e){
    this.setData({
      firstname: ''
    })
  },

  onClearItraId:function(e){
    this.setData({
      itraId: ''
    })
  },
 
  bindItemChange(e){
      this.setData({
        currentIndex:e.detail.current
      })
  },

  //加载关注
  onShow(){
    this.loadFav();
  },
  loadFav(){
    var strf = wx.getStorageSync('myfavs');
    if(strf!=null && strf!=''){
      var listFav = JSON.parse(strf);
      this.setData({
          list:listFav
      });
    }
  },
  handleTabLeft(){
    if(this.data.currentTab==0) return;
    this.setData({
      currentTab:0
    })
  },
  handleTabRight(){
    if(this.data.currentTab==1) return;
    this.setData({
      currentTab:1
    })
  },
  getnotice(){
    const app = getApp();
    wx.request({
      url: app.globalData.notice_url,
      method:"GET",
      success:(res)=>{
        var results = res.data;
        console.log(results);
        if(results!=null && results!=''){
          this.setData({
            notice_text:results
          }
          )
        }
      },
      fail: (err) => {
      }
    })
  },
})
